<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/6/11
 * Time: 10:24
 */

namespace app\applet\model;


use think\Db;
use think\Exception;

class StoreOrder
{

    /**
     * 统计商家待发货 待收货 待商家回复的评价  待审核售后的条数
     */
    public function getCount($store_id){
        //待发货订单条数
        $data['delivery_count']=Db::name('order')->where(['store_id'=>$store_id,'status'=>2])->count();
        $data['received_count']=Db::name('order')->where(['store_id'=>$store_id,'status'=>3])->count();
        $data['comment_count']=Db::name('comment')->where(['store_id'=>$store_id,'is_reply'=>2])->count();
        $data['after_sales_count']=Db::name('order_after_sale')
            ->where(['store_id'=>$store_id,'status'=>1])->count();

        return $data;
    }

    /**
     * 商家订单列表   type 1=待发货  2=待收货  3=售后订单  4=待回复评价
     *              status 售后类型  1=全部  2=退款 3=退货退款
     *              reply_type 评价类型  2=未回复  1=已回复
     */
    public function orderList($store_id,$type,$page,$page_size,$status=1,$reply_type=1){
        $where=[];
        if($type==1){
            $where['status']=2;
        }elseif($type==2){
            $where['status']=3;
        }elseif($type==3){
            if($status==1){
                $where['oas.after_type']=['in',[1,2]];
            }elseif($status==2){
                $where['oas.after_type']=1;
            }else{
                $where['oas.after_type']=2;
            }
        }else{
            if($reply_type==1){
                $where['c.is_reply']=1;
            }else{
                $where['c.is_reply']=2;
            }
        }

       /* $data=Db::name('order_goods')->alias('og')
            ->field('o.order_id,o.status,og.goods_name,og.spec_name,og.goods_num,og.score_money,og.coin_money')
            ->join('order o','o.order_id=og.store_id')
            ->join('goods g','og.goods_id=g.goods_id')
            ->where(['o.store_id'=>$store_id])
            ->where($where)
            ->page($page,$page_size)
            ->select();*/
       if($type==1||$type==2){
           $data=Db::name('order')
               ->field('order_id,order_sn,status,log_sn,log_id')
               ->where(['store_id'=>$store_id])
               ->where($where)
               ->page($page,$page_size)
               ->select();

           if(!empty($data)){
               foreach($data as $k=>&$v){
                   //商品
                   $goods_list=Db::name('order_goods')->alias('og')
                       ->field('og.og_id as order_goods_id,og.goods_id,og.goods_name,og.spec_name,og.goods_num,
                    og.score_money,og.coin_money,g.cover_pic')
                       ->join('goods g','g.goods_id=og.goods_id')
                       ->where(['og.order_id'=>$v['order_id']])
                       ->select();
                   $v['goodsList']=$goods_list;
               }
           }

           $count= Db::name('order')
               ->where(['store_id'=>$store_id])
               ->where($where)
               ->count();

       }

       if($type==3){
           $field='oas.oas_id,oas.after_type,oas.status,oas.type,oas.order_id';
           $field2='og.goods_name,og.spec_name,og.goods_num,og.score_money,og.coin_money,g.cover_pic';
           $data=Db::name('order_after_sale')->alias('oas')
               ->field($field)
               //->join('order_goods og','oas.order_goods_id=og.og_id')
               //->join('goods g','g.goods_id=og.goods_id')
               ->where(['oas.store_id'=>$store_id,'oas.is_del'=>1])
               ->where($where)
               ->page($page,$page_size)
               ->select();
           //商品数据
           foreach ($data as $k=>&$v){
               $goods_list=Db::name('order_goods')->alias('og')
                   ->field($field2)
                   ->join('goods g','g.goods_id=og.goods_id')
                   ->where(['og.order_id'=>$v['order_id']])
                   ->select();
               $v['goodsList']=$goods_list;

           }

           $count=Db::name('order_after_sale')->alias('oas')
               //->join('order_goods og','oas.order_goods_id=og.og_id')
               //->join('goods g','g.goods_id=og.goods_id')
               ->where('oas.store_id',$store_id)
               ->where($where)
               ->count();
       }

       if($type==4){
            $data=Db::name('comment')->alias('c')
                ->field('c.c_id,c.order_id,c.order_sn,c.star,c.content,m.nickName,m.avatarUrl,c.is_reply,c.reply')
                ->join('member m','m.member_id=c.member_id')
                ->where('c.store_id',$store_id)
                ->where($where)
                ->page($page,$page_size)
                ->select();
           $count=Db::name('comment')->alias('c')
               ->join('member m','m.member_id=c.member_id')
               ->where('c.store_id',$store_id)
               ->where($where)
               ->count();

           $list['reply_count'] = Db::name('comment')->alias('c')
                    ->join('member m','m.member_id=c.member_id')
                    ->where(['c.store_id'=>$store_id,'c.is_reply'=>2])
                    ->count();

       }


        $list['current_page'] = $page;
        $list['total_page'] =ceil($count / $page_size);
        $list['page_num'] = $page_size;
        $list['total_num'] = $count;
        $list['data'] = $data;

        return $list;

    }

    /**
     * 售后订单详情
     */
    public function orderDetail($after_id,$store_id){
        $field='o.order_id,o.order_sn,o.create_time,o.pay_time,oas.after_type,oas.after_reason,oas.after_sn,
        oas.status,oas.type,sa.company_name,oas.refuse_reason';
        $field2='og.goods_name,og.spec_name,og.goods_num,og.score_money,og.coin_money,
        og.delivery_fee,g.cover_pic';

        $data=Db::name('order_after_sale')->alias('oas')
            ->field($field)
            ->join('order o','o.order_id=oas.oas_id')
//            ->join('order_goods og','og.og_id=oas.order_goods_id')
            ->join('store_apply sa','sa.sa_id=oas.store_id')
//            ->join('goods g','g.goods_id=og.goods_id')
            ->where(['oas.store_id'=>$store_id,'oas.oas_id'=>$after_id])
            ->find();
            $goods_list=Db::name('order_goods')->alias('og')
                ->field($field2)
                ->join('goods g','g.goods_id=og.goods_id')
                ->where(['og.order_id'=>$data['order_id']])
                ->select();
            $data['goods_list']=$goods_list;

        return $data;

    }

    /**
     * 评价回复
     */
    public function reply($store_id,$c_id,$content){
        Db::name('comment')
            ->where(['c_id'=>$c_id,'store_id'=>$store_id])
            ->update(['reply'=>$content,'is_reply'=>1,'update_time'=>time()]);
        return true;
    }

    /**
     * 商家发货操作页面
     */
    public function deliveryPage($order_id,$store_id){
        $data=Db::name('order')->field('order_id,receiver,re_phone,address')
            ->where(['store_id'=>$store_id,'order_id'=>$order_id])
            ->find();
        return $data;
    }

    /**
     * 商家发货提交
     */
    public function deliveryPost($order_id,$store_id,$data){
        Db::name('order')->where(['store_id'=>$store_id,'order_id'=>$order_id])
            ->update($data);
        Db::name('order_goods')->where(['order_id'=>$order_id])
            ->update(['og_d_status'=>2,'update_time'=>time()]);

        return true;
    }


    /**
     * 售后---退款，退货操作
     *          status  1=同意  2=拒绝
     */
    public function afterRefund($store_id,$data){
        $status=$data['status'];
        $info=Db::name('order_after_sale')
            ->field('order_id,order_goods_id as og_id,order_status,member_id')
            ->where('oas_id',$data['oas_id'])->find();

        if($status==1){
            //金币和积分退款    -----------------------微信退款暂时没有写--------------
            $this->refund($info);
            Db::name('order_after_sale')
                ->where(['store_id'=>$store_id,'oas_id'=>$data['oas_id']])
                ->update(['status'=>5]);

            Db::name('order')->where('order_id',$info['order_id'])
                ->update(['status'=>10]);

            //return true;
        }else{
            Db::name('order_after_sale')
                ->where(['store_id'=>$store_id,'oas_id'=>$data['oas_id']])
                ->update(['status'=>3,'refuse_reason'=>$data['refuse_reason']]);

            Db::name('order')
                ->where(['member_id'=>$info['member_id'],'order_id'=>$info['order_id']])
                ->update(['status'=>$info['order_status'],'update_time'=>time()]);
        }

        return true;
    }

    /**
     * 退款
     */
    public function refund($input){
        $orderID=$input['order_id'];
        $ogId=$input['og_id'];
        //获取订单商品信息
        $orderGoods=Db::name("order_goods")->where(['og_id'=>$ogId,'order_id'=>$orderID])->find();
        //获取记录
        $assetLogList=Db::name("member_asset_log")
            ->where(['relation_id' => $orderID,'change_type'=>3,'relation_sid'=>$ogId,'log_type_id'=>['in',['58,29,47,60']]])
            ->select();
        $store_id=Db::name("order")->where(['order_id'=>$orderID])->value("store_id");
        Db::startTrans();
        try{
            //7天信誉记录资产处理
            foreach ($assetLogList as $log){
                $member_id=$log['member_id'];
                $log_type_id=$log['log_type_id'];
                $amount=$log['amount'];
                $mal_id=$log['mal_id'];
                $num=Db::name("member_asset_log")
                    ->where(['member_id'=>$member_id,'mal_id'=>$mal_id])
                    ->delete();
                if($num<=0){
                    throw new Exception("更新失败");
                }
                if(in_array($log_type_id,[58,47,29])){//删除推荐赠送 7天信誉冻结
                    $num=Db::name("member_asset")->where(['member_id'=>$member_id])
                        ->setDec("seven_frozen_score", $amount);
                    if($num<=0){
                        throw new Exception("更新失败");
                    }
                }elseif($log_type_id==60){//商家卖出扣除金币退还
                    if($store_id>0){
                        $store_member_id=Db::name("store_apply")->where(['sa_id'=>$store_id])->value("member_id");
                        $sql="update mm_member_asset set coin=coin+$amount,frozen_coin=frozen_score-$amount,
                          seven_frozen_coin=seven_frozen_coin-$amount where member_id=".$store_member_id."  
                          and frozen_coin>=$amount and seven_frozen_coin>=$amount";
                        $num=Db::query($sql);
                        if($num<=0){
                            throw new Exception("更新失败");
                        }
                    }
                }
            }
            //退款
            //暂时全部退到积分金币里
            $score_money=$orderGoods['score_money'];
            $coin_money=$orderGoods['coin_money'];
            $order_member_id=Db::name("order")->where(['order_id'=>$orderID])->value("member_id");
            $sql="update mm_member_asset set coin=coin+$coin_money,score=score+$score_money where member_id=".$order_member_id;
            $num=Db::query($sql);
            if($num<=0){
                throw new Exception("更新失败");
            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
        }
    }

    /**
     * 查询商家id
     */
    public function selectStore($member_id){
        $store_id=Db::name('store_apply')->where(['member_id'=>$member_id,'status'=>1])
            ->value('sa_id');
        return $store_id;
    }
}